package main

//go:generate go run generate.go

import (
	"bufio"
	"context"
	"fmt"
	"github.com/gorilla/mux"
	"github.com/spf13/viper"
	"golang.org/x/net/websocket"
	"net/http"
	"regexp"
	"runtime/debug"
	"sevlteServer/auto"
	"sevlteServer/service"
	"sevlteServer/tool"
	"sevlteServer/ws"
	_ "sevlteServer/ws"
	"sort"
	"strings"
	"sync"
)

func crashed(ctx context.Context) {

	reader := bufio.NewReader(strings.NewReader(string(debug.Stack())))

	n := 7
	var panicStack []string
	for i := 0; ; i++ {
		line, _, err := reader.ReadLine()
		if i == n || i == n+1 {
			panicStack = append(panicStack, string(line))
		}
		if err != nil || i > n+1 {
			break
		}
	}
}

func restoreLog() {
}

func disableLog(r *http.Request) bool {

	return true
}

var rIsAPI = regexp.MustCompile(`(?i)^/api/(.*)?$`)

var (
	rWxIOS     = regexp.MustCompile(`(iPhone)(.*)(MicroMessenger)`)
	rWxAndroid = regexp.MustCompile(`(Android)(.*)(MicroMessenger)`)
	rMacWx     = regexp.MustCompile(`\(Macintosh; .*(?P<osVer> \d*_\d*_\d*\)).* MicroMessenger/(?P<wxVer>\d*\.\d*\.\d*)\((?P<wxVerHex>.*)\) MacWechat`)
	rWinWx     = regexp.MustCompile(`\(Windows \S* (?P<osVer>\d*\.\d*)(; )?(?P<subSys>\S*)\).* MicroMessenger/(?P<wxVer>\d*\.\d*\.\d*)`)
	rIsWx      = regexp.MustCompile(`MicroMessenger`)
	rMobile    = regexp.MustCompile(`(Android|iPhone)`)
)

func reqProc(reqPath string, w http.ResponseWriter, r *http.Request) {
	//以单例运行
	var shortLiveMutex sync.Mutex

	if rIsAPI.MatchString(r.URL.Path) {
		shortLiveMutex.Lock()

		shortLiveMutex.Unlock()

		defer func() {
		}()
	}

	defer func() {

	}()

	if disableLog(r) {
		defer restoreLog()
	}
}
func WebServe(_ []string) {
	service.Enroll()

	defer tool.DbPool.Close()

	viper.SetConfigName(".configure")
	viper.SetConfigType("json")
	viper.AddConfigPath("./")
	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			// 配置文件未找到错误；如果需要可以忽略
			fmt.Println("File not found")
		} else {
			// 配置文件被找到，但产生了另外的错误
		}
	}

	host := "localhost"
	if viper.IsSet("server.host") {
		host = viper.GetString("server.host")
	}

	httpPort := 8888
	if viper.IsSet("server.port") {
		httpPort = viper.GetInt("server.port")
	}
	fmt.Println(host)
	fmt.Println(httpPort)

	addr := fmt.Sprintf(":%v", httpPort)

	route := mux.NewRouter()

	//route.HandleFunc("/", Handle)

	var rootExists bool
	var pathList []string
	for k := range auto.Services {
		if k == "/" {
			rootExists = true
			continue
		}
		pathList = append(pathList, k)
	}
	fmt.Println(rootExists)
	sort.Strings(pathList)
	for _, k := range pathList {
		k := k
		route.HandleFunc(k, func(w http.ResponseWriter, r *http.Request) {
			auto.Services[k].Fn(r, w)
		})
	}

	route.Handle("/ws", websocket.Handler(ws.WsHandle))

	serv := &http.Server{
		Addr:    addr,
		Handler: GzipHandler(route),
	}

	serv.ListenAndServe()
	//http.ListenAndServe(addr, nil)
}
